import axios from 'axios'
import Cookies from 'js-cookie'
import Router from "@/router";
import {
	getToken,
	removeToken
} from '@/utils/auth'
import config from '@/utils/config'

// 引入英文语言包
import zhLocale from '@/i18n/langs/zn';
import enLocale from '@/i18n/langs/en';

import {
	Dialog
} from "vant";

const locale = Cookies.get('locale') || 'zh'
const langs = locale == 'zh' ? zhLocale.language : enLocale.language

// create an axios instance
const service = axios.create({
	baseURL: config.baseURL,
	// withCredentials: true, // send cookies when cross-domain requests
	timeout: 500000 // request timeout
})

// request interceptor
service.interceptors.request.use(
	config => {
		// do something before request is sent
		if (config.method) {
			config.params = {
				...config.params
			}
		}
		
		if(getToken()) {
			config.headers['authorization'] = `Bearer ${getToken()}`
		}
		
		if (config.method === 'post' ||
			config.method === 'put' ||
			config.method === 'delete') {
			config.data = {
				...config.data
			}
			
			let hotels = localStorage.getItem('hotels')
			if(hotels) {
				hotels = JSON.parse(hotels)
				Object.assign(config.data, {
					hotel_id: hotels.hotel_id
				})
			}
		}
		
		return config
	},
	error => {
		console.log(error) // for debug
		return Promise.reject(error)
	}
)

// response interceptor
service.interceptors.response.use(
	response => {
		
		const res = response.data
		// if the custom code is not 200, it is judged as an error.
		if (res.status_code !== 200) {
			// 提示
			// 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
			// if (res.status_code == 401) {
			// 	removeToken()
			// 	localStorage.removeItem("userinfo");
			// 	localStorage.removeItem("hotels");
			// 	Router.replace(`/login`);
			// 	return
			// }
			if(res.message.indexOf('没有权限') > -1) {
				Dialog.alert({
					title: langs.text74,
					message: langs.text75,
					confirmButtonText: langs.text25
				}).then(() => {});
				return
			}
			Dialog.alert({
				title: langs.text74,
				message: res.message,
				confirmButtonText: langs.text25
			}).then(() => {});
			return Promise.reject(new Error(res.message || 'Error'))
		} else {
			return res
		}
	},
	error => {
		if(/401/.test(error)) {
			removeToken()
			localStorage.removeItem("userinfo");
			localStorage.removeItem("hotels");
			Router.replace(`/login`);
		}
		if(/没有权限/.test(error)) {
			Dialog.alert({
				title: langs.text74,
				message: langs.text75,
				confirmButtonText: langs.text25
			}).then(() => {});
		}
		if(/500/.test(error)) {
			// 提示
			Dialog.alert({
				title: langs.text74,
				message: error,
				confirmButtonText: langs.text25
			}).then(() => {});
		}
		return Promise.reject(error)
	}
)

export default service
